package com.zll.dms.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zll.dms.exception.MyBaseException;
import com.zll.dms.mapper.RoleMapper;
import com.zll.dms.mapper.UserMapper;
import com.zll.dms.model.Role;
import com.zll.dms.model.User;
import com.zll.dms.model.dto.UserRoleDto;
import com.zll.dms.service.UserService;
import com.zll.dms.utils.CommonUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.UnauthenticatedException;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RoleMapper roleMapper;

    @Override
    public User getNowUserInfo() {
        Subject subject = SecurityUtils.getSubject();
        String userName = subject.getPrincipal().toString();
        List<User> userFulls = userMapper.getUserFullByName(userName);
        if (CollectionUtils.isEmpty(userFulls)) {
            subject.logout();
            throw new UnauthenticatedException("当前用户不存在，请重新登陆");
        }
        User user = userFulls.get(0);
        user.setPassword(null);
        return user;
    }

    @Override
    public PageInfo<User> getUserList(String userName, int nowPage, int pageSize) {
        PageHelper.startPage(nowPage, pageSize);
        List<User> usersPage = userMapper.getUsersPage(userName);
        //封装role列表
        if (CollectionUtils.isNotEmpty(usersPage)) {
            Set<Long> userIds = usersPage.stream().map(User::getId).collect(Collectors.toSet());
            //获取分页数据里user的角色列表
            List<UserRoleDto> userRoleDtos = roleMapper.getRolesByUserIds(userIds);
            if (CollectionUtils.isNotEmpty(userRoleDtos)) {
                //有对应的角色列表 就构成userid-》role列表映射
                Map<Long, List<Role>> userIdRolesMap = new HashMap<>();
                for (UserRoleDto userRoleDto : userRoleDtos) {
                    List<Role> roles = userIdRolesMap.get(userRoleDto.getUserId());
                    if (roles == null) {
                        roles = new ArrayList<>();
                        roles.add(userRoleDto.getRole());
                        userIdRolesMap.put(userRoleDto.getUserId(), roles);
                    }else {
                        roles.add(userRoleDto.getRole());
                    }
                }
                //放进user列表
                for (User user : usersPage) {
                    Long id = user.getId();
                    user.setRoleList(userIdRolesMap.get(id));
                }
            }
        }
        return new PageInfo<User>(usersPage);
    }

    @Override
    public void deleteUser(long id) {
        int i = userMapper.deleteUser(id);
        if (i <= 0) {
            throw new MyBaseException("删除用户失败");
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateRole(Long userId, List<Long> roleIds) {
        int result = userMapper.deleteRole(userId);

        if (CollectionUtils.isNotEmpty(roleIds)) {
            result = userMapper.insertRole(userId, roleIds);
            if (result <= 0) {
                throw new MyBaseException("修改用户角色出错");
            }
        }
    }

    @Override
    public void updatePw(Long id, String newPw) {
        int result = userMapper.updatePassword(id, newPw);
        if (result <= 0) {
            throw new MyBaseException("修改用户密码出错");
        }
    }

    @Override
    public void updateUser(User user) {
        User currentUser = CommonUtils.getCurrentUser(userMapper);
        if (!StringUtils.equals(user.getPassword(), currentUser.getPassword())) {
            throw new MyBaseException("密码不正确，请确认密码");
        }
        if (StringUtils.isNotBlank(user.getNewPassword())) {
            user.setPassword(user.getNewPassword());
        }
        user.setId(currentUser.getId());
        int i = userMapper.updateUser(user);
        if (i <= 0) {
            throw new MyBaseException("修改用户错误");
        }
    }

    @Override
    public User getUserNow() {
        Long currentUserId = CommonUtils.getCurrentUserId(userMapper);
        User user = userMapper.getUserById(currentUserId);
        return user;
    }


}
